package dao

import (
	"context"
	"device-admin/internal/dal"
	"device-admin/internal/models"

	"github.com/golang-module/carbon/v2"
)

type TaskRecord struct{}

// Add 新增任务记录
func (TaskRecord) Add(ctx context.Context, query *dal.Query, records []*models.TaskRecord) {
	tr := query.TaskRecord
	for _, record := range records {
		count, _ := tr.WithContext(ctx).
			Where(tr.RobotID.Eq(record.RobotID)).
			Where(tr.BeginTime.Eq(record.BeginTime)).
			Count()
		if count <= 0 {
			tr.WithContext(ctx).Create(record)
		}
	}
}

// SummaryDuration 统计时长
// workType 工作类型 0-未知 1-运营任务 2-充电任务 3-出门任务
func (TaskRecord) SummaryDuration(
	ctx context.Context,
	query *dal.Query,
	robotID string,
	date string,
	workType int,
) (timeDuration int64) {
	date = carbon.Parse(date).Layout("2006-01-02") // 规范日期格式
	tr := query.TaskRecord
	record, _ := tr.WithContext(ctx).
		Where(tr.RobotID.Eq(robotID)).
		Where(tr.CreatedDate.Eq(date)).
		Where(tr.WorkType.Eq(workType)).
		Select(tr.TimeDuration.Sum().As("time_duration")).
		Take()
	if record != nil {
		return record.TimeDuration
	}
	return 0
}

// SummaryOdometer 统计任务里程
func (TaskRecord) SummaryTaskActiveInfo(
	ctx context.Context,
	query *dal.Query,
	robotID string,
	date string,
) (
	totalOdometer int64,
	totalTimeDuration int64,
	totalRunCount int64,
) {
	date = carbon.Parse(date).Layout("2006-01-02") // 规范日期格式
	var taskSummary struct {
		TotalOdometer     int64 `gorm:"column:total_odometer"`
		TotalTimeDuration int64 `gorm:"column:total_time_duration"`
		TotalRunCount     int64 `gorm:"column:task_run_count"`
	}
	tr := query.TaskRecord
	tr.WithContext(ctx).
		Where(tr.RobotID.Eq(robotID)).
		Where(tr.CreatedDate.Eq(date)).
		Where(
			tr.WithContext(ctx).
				Where(tr.TotalIndex.Gt(1)).
				Or(tr.WorkType.Eq(1)),
		).
		Select(
			tr.Odometer.Sum().As("total_odometer"),
			tr.TimeDuration.Sum().As("total_time_duration"),
			tr.ID.Count().As("task_run_count"),
		).
		Scan(&taskSummary)
	return taskSummary.TotalOdometer, taskSummary.TotalTimeDuration, taskSummary.TotalRunCount
}
